﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Routing;

using MvcEngine.Core;
using MvcEngine.Core.Repositories;
using System.IO;
using MvcEngine.Core.Helpers;
using MvcEngine.Core.Extensions;
using MvcEngine.Core.Configuration;

namespace MvcEngine.Core.HttpHandlers
{
    public class FileHandler : IHttpHandler
    {
        private RouteData routeData = null;
        private IFileResolver fileResolver = null;

        public FileHandler(RouteData routeData, IFileResolver fileResolver)
        {
            this.routeData = routeData;
            this.fileResolver = fileResolver;
        }

        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return false; }
        }

        public virtual void ProcessRequest(HttpContext context)
        {
            string filePath = fileResolver.GetFilePath(routeData);

            if (!FileHelper.Current.Exists(filePath))
            {
                context.Response.Write("File not found.");
                context.Response.End();
                return;
            }

            string extension = Path.GetExtension(filePath).Remove(0, 1);

            ExtensionConfigurationElement element = ConfigurationUtil.Current.Extensions.GetElement(extension);
            if (element != null && element.Type == "image")
            {
                context.Response.ContentType = element.ContentType;
            }
            else
            {
                context.Response.ContentType = "application/octet-stream";
                context.Response.AppendHeader("Content-Disposition", "inline; filename=\"" + Path.GetFileName(filePath) + "\"");
            }

            context.Response.Cache.SetCacheability(HttpCacheability.Public);
            context.Response.Cache.SetExpires(DateTime.Now.AddYears(1));
            context.Response.TransmitFile(filePath);
            context.Response.End();
        }

        #endregion
    }
}
